package com.app.timertask;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;

import com.app.dao.ImagesDao;
import com.app.entity.Images;

public class ImagesTimerTask {
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ImagesDao imagesDao;
	
	@Autowired
	WebApplicationContext context;
	
	public void deleteImages() throws IOException{
		int num = 0;
		long startTime = System.currentTimeMillis();
		List<Images> imgList = imagesDao.findAllNotInUseImages();
		StringBuffer sb = new StringBuffer();
		String saveDirectory = context.getServletContext().getRealPath("common/userfiles/image/");
		
		for (Images img : imgList) {
			File file = new File(saveDirectory, img.getRenameAs());
			if (file.exists()){
				file.delete();
				sb.append(img.getRenameAs()).append(",  ");
				num++;
			}
		}
		
		imagesDao.deleteAllImages(imgList);
		
		long endTime = System.currentTimeMillis();
		
		if(num > 0){
			logger.info("定时任务用时：{}毫秒，共删除{}个文件，文件名分别为：{}",new Object[]{endTime - startTime,num,sb.toString()});	
		} else {
			logger.info("定时任务用时：{}毫秒，共删除0个文件.",endTime - startTime);	
		}
		
	}
}
